
const log4js = require('./log4j')
const jwt = require('jsonwebtoken')

const jwtKey = 'CodingXiaoShi_Nuttertools'


const CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001, // 参数错误
  USER_ACCOUNT_ERROR: 20001, // 账号或密码错误
  USER_LOGIN_ERROR: 30001, // 用户未登录
  BUSINESS_ERROR: 4000, // 业务请求失败
  AUTH_ERROR: 50001, // 认证失败或token过期
}

const pager = ({ pageNum = 1, pageSize = 10 }) => {
  pageNum *= 1
  pageSize *= 1
  const skipIndex = (pageNum - 1) * pageSize;
  return {
    page: {
      pageNum,
      pageSize,
    },
    skipIndex
  }
}

const success = (data = '', msg = '', code = CODE.SUCCESS) => {
  // log4js.debug(data)
  return { code, data, msg }
}

const fail = (msg, data, code = CODE.BUSINESS_ERROR) => {
  log4js.debug(msg, data)
  return {
    code, data, msg
  }
}

const decoded = (authorization) => {
  if (authorization) {
    const token = authorization.split(' ')[1]
    return jwt.verify(token, jwtKey)
  }
  return ''
}


const getTreeMenu = (source, id, list) => {
  for (const item of source) {
    if (item.parentId.slice().pop() === (id ? id.toString() : id)) {
      list.push(item._doc)
    }
  }
  list.forEach(item => {
    item.children = [];
    getTreeMenu(source, item._id, item.children);
    if (item.children.length === 0) {
      delete item.children;
    } else if (item.children.length > 0 && item.children[0].menuType === 2) {
      item.action = item.children;
    }
  })
  return list
}

module.exports = {
  // 页码处理
  jwtKey,
  pager,
  success,
  fail,
  getTreeMenu,
  decoded,
  CODE,
}
